<template>
  <div>
    <!--    <hte-file-class-form ref="realForm" @ok="submitCallback" :disabled="disableSubmit"></hte-file-class-form>-->
    <a-form-model :model="hteFile" ref="mainForm"  :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" :rules="rules">
      <a-form-model-item label="文件类型" prop="classId">
        <a-tree-select
          v-model="hteFile.classId"
          :tree-data="treeData"
          placeholder="请选择文件类型"
          tree-default-expand-all
          @change="handleChangeClass"
        >
        </a-tree-select>
      </a-form-model-item>
    </a-form-model>

    <div class="table-operator">
      <a-button icon="download" @click="handleTemplate" :disabled="!classId">下载模板</a-button>
      <a-button icon="plus" @click="handleShowExcel" :disabled="!classId">粘贴导入</a-button>
      <a-button style="margin-left: 10px; margin-bottom: 10px" icon="delete" @click="deleteAttach"> 删除 </a-button>
    </div>
    <!-- table区域-begin -->
    <div>
       <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                  <template slot="title">
                    文件属性原则：<br />  
                    1、文件名称和文件上传“正文附件名称”保持一致。<br />
                  </template>
      <a-table
        ref="table"
         :scroll="{x:true}"
        bordered
        row-key="rowKey"
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        class="j-table-force-nowrap"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      />
       </a-tooltip>
    </div>

    <ExcleEditor ref= 'excleEditor' v-if="showExcleEditor" :headers="excelHeader" :loading="excelLoading" @close="closeExcleEditor" />
  </div>
</template>

<script>
import {  getAction } from '@/api/manage';
import ExcleEditor from './ExcleEditor';
import cloneDeep from 'lodash/cloneDeep'
import { policylLevel,flagDics} from '@/views/library/dics'
import { isDateYYYYMMDD,isNumber,isArea } from '@/utils/validate'
const baseColumnsNormal = [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
           required:true
        },
        {
          title: '文件编号',
          dataIndex: 'fileNo',
           required:true
        },
        {
          title: '关键词',
          dataIndex: 'keywords',
           required:false
        },
         {
          title: '文件用途',
          dataIndex: 'purpose',
           required:false
        },
      ]
      const baseColumns=[
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          required:true
        },
      ]
export default {
  name: 'FilesContent',
  components: { ExcleEditor },
  props: {
  
    parentId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
        hteFile: {
          classId :''
        },
      rules:{classId:[{ required: true, message: '请选择文件类型' }]},
      treeData: [],
      label:'',
      classAttrList: [],
      form: this.$form.createForm(this, { name: 'coordinated' }),
      classId:null,
      columns:[],
      excelHeader: [],
      showExcleEditor: false,
      tableData: [],
      title: '',
      width: 800,

      disableSubmit: false,
      data: [],
      selectedRowKeys: [],
      rowKeyIndex: -1,
      addVisible: false,
      confirmLoading: false,
      model: { objectType: 1, client: '海芯', objectId: [] },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      objData: [],
      fetching: false,
      urls: {
        getTreeList: '/lib/hteFileClass/getTreeList',
        listAttr: '/lib/hteLibFile/attrs',
        foodTypeTree: '/lib/hteDict/foodTypeTree',
        standardKeyword: '/lib/hteDict/standardKeyword',
        queryByIds: '/lib/hteLibFile/queryByIds/',
        specialList: "/policy/policySpecial/list",
        mechanismList: "/policy/policyMechanism/list",
        businessList: "/policy/policyBusiness/list",
        areaInfo:'/manage/codeInfo/areaInfo',
        codeInfo:'/manage/codeInfo/list'
      },
      excelLoading:false,
      specialList:[],
      businessList:[],
      selectSearchData:[],
      areaInfo:[],
      policylLevel:[],
      qualificationList:[],
      industryList:[],
    };
  },
 
  created() {
    //this.classId = this.parentId
    this.fetchClassTree();
      
    
    
  },
  methods: {
    initDics(){
      getAction(this.urls.specialList, {pageNo: 1, pageSize: -1 }).then(res => {
        if (res.success) {
          this.specialList= res.result.records
        }
      })
      getAction(this.urls.businessList, {  pageNo: 1, pageSize: -1 }).then(res => {
        if (res.success) {
          this.businessList= res.result.records
        }
      })
 
     
      getAction(this.urls.areaInfo, {  pageNo: 1, pageSize: -1 }).then(res => {
        if (res.success) {
          let areaInfo = []
          this.getAllArea(res.result,areaInfo)
          this.areaInfo= areaInfo 
        }
      })
        getAction(this.urls.mechanismList, {  pageNo: 1, pageSize: -1 }).then(res => {
        if (res.success) {
            this.mechanismList = res.result.records
            // this.$forceUpdate()
        }
      })
       getAction(this.urls.codeInfo, {column:"code",order:"Asc",pageNo:0,pageSize:-1,isdel:false,type:'政策库政策级别' }).then(res => {
        if (res.success) {
        
          this.policylLevel= res.result.records
        }
      })
    },
    getAllArea(data,allArr){
        data.forEach((it,i) => {
            allArr.push(it.label);
            if( !!it.children && it.children.length > 0){
                 this.getAllArea(it.children,allArr)
            }
      })
       getAction(this.urls.codeInfo, {column:"code",order:"Asc",pageNo:0,pageSize:-1,isdel:false,type:'政策库政策级别' }).then(res => {
        if (res.success) {
          this.policylLevel= res.result.records
        }
      })


       getAction('/libraryCompany/hteLibCompanySize/industryNameList',{}).then(res=>{
            this.industryList = res.result.records
        });
      getAction(this.urls.codeInfo, {column:"code",order:"Asc",pageNo:0,pageSize:-1,isdel:false,type:'企业资质' }).then(res => {
        if (res.success) {
          this.qualificationList= res.result.records
        }
      })
    },
    fetchClassTree() {
      let that = this
      this.columns = []
     this.tableData = []
      getAction(this.urls.getTreeList, { parentId: this.parentId }).then(res => {
        if (res.success) {
          if(this.parentId == 2){
            this.selectableTreeData(res.result.treeList)
            that.initDics();
          }
          this.treeData = res.result.treeList;
          
           
          // that.classId = ''
          // that.hteFile.classId =  that.classId
          // that.$emit('changeClass',that.classId);
          that.fetchClassAttr();
          
        } else {
          this.$message.error('获取分类树错误');
        }
      });
    },
     selectableTreeData(data){
       data.forEach((it,i) => {
             it.selectable = false
            if( !it.children || it.children.length == 0){
                it.selectable = true
            }else{
              this.selectableTreeData(it.children)
            }
            
      })
    },
    handleDel() {

    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },

    deleteAttach() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请选中要删除的记录');
        return false;
      }
      
      const that = this;
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中记录吗?',
        onOk: function() {
          that.selectedRowKeys.forEach(key => {
            const idx = that.tableData.findIndex((value)=>value.rowKey==key)
            if(idx!=-1){
                that.tableData.splice(idx,1);  
            }
            
          });
          that.selectedRowKeys = []

        }
      });
    },

    handleShowExcel() {
      this.excelLoading = false
      let pass = true
      const that = this
       this.$refs.mainForm.validate((vaild,values) => {
        if (!vaild) {
          console.info(err);
          pass = false
        }else{
           that.showExcleEditor = true;
          that.fetchClassAttr();
        }
      });
      if(!pass){
        that.$message.error('请选择文件类型');
        return false
      }
    
    },
    closeEdit(){
      this.$refs.excleEditor.destroy();
      this.showExcleEditor = false;
      this.excelLoading = false
        
    },
    closeExcleEditor(data) {
      let that = this
      this.excelLoading = true
      if(!data){
        this.closeEdit();
       
        return false;
      }
      const appendList = [];
      if (data && data.length > 0) {
        for (const sheet of data) {
          // debugger;
          const rows = sheet.data;
          for (const row of rows) {
            const appendData = [];
            let index = 0;
            let notEmptyRow = false;
            for (const cell of row) {
              // if (index > 26) {
              //   break;
              // }
              index++;
              if (cell && cell.m) {
                notEmptyRow = true;
                appendData.push(cell.m);
              } else {
                appendData.push('');
              }
            }
            if (notEmptyRow) {
              appendList.push(appendData);
            }
          }
        }
      }
      console.log('要导入的数据' + appendList);
      if (appendList.length < 2) {
          this.closeEdit();
          return false;
      }
      let importArr = [];
      for (let i = 1; i < appendList.length; i++) {
        const dataRow = appendList[i];
        let tableRow = {};
        tableRow['attrs']= {};
        for (let j = 0; j < dataRow.length && j < this.columns.length -1 ; j++) {
          //第一列是序号
          let columnsIndex = j + 1
          //空格转换
          debugger
          let cellData = dataRow[j].replace(/\r/gi, '').replace(/\n/gi, '').replace(/\s+/,' ')
          let title = this.columns[columnsIndex].title;
          if(this.parentId == 2 && !!cellData ){
            //政策库数据验证
           if(!that.checkData2(title,cellData,tableRow)){
              this.excelLoading = false
             return false
           }
          }
          if (this.columns[columnsIndex].dataIndex.indexOf('attrs') == 0) {
            
            if(this.columns[columnsIndex].required && !cellData ){
               this.$message.error(`${this.columns[columnsIndex].title}文件属性必填！`);
                this.excelLoading = false
               return false;
            }
            if(cellData.length > 4000){
              this.$message.error(`${this.columns[columnsIndex].title}文件属性内容长度大于4000字！`);
              this.excelLoading = false
               return false;
            }
            this.$set(tableRow.attrs, this.columns[columnsIndex].dataIndex.split('.')[1], cellData);
          } else {
            //基本信息
            if(this.columns[columnsIndex].required && !cellData ){
               this.$message.error(`${this.columns[columnsIndex].title}文件属性必填！`);
               this.excelLoading = false
               return false;
            }

            this.$set(tableRow, this.columns[columnsIndex].dataIndex,cellData);
        
            
          }
        }
        tableRow['rowKey'] = i + tableRow.fileName;
        let checkFile = importArr.find(item=>{
          return item.fileName == tableRow.fileName
        })
         let checkFile2 = this.tableData.find(item=>{
          return item.fileName == tableRow.fileName
        })
        if(checkFile || checkFile2 ){
           this.$message.error(`${tableRow.fileName}文件名重复！`); 
            this.excelLoading = false
           return false; 
        }

        //文件大类
        this.$set(tableRow, 'libraryType',this.parentId);
        importArr.push(tableRow);
      }
      
      this.tableData.push(...importArr)
      console.log(JSON.stringify(this.tableData));
      this.closeEdit();
      
    },
    handleBusiness(value){
      let business =this.businessList.find(item=>{
        return item.name === value
      })
      return business&&business.code || '';
       
    },
    checkData2(title,cellData,tableRow){
      //数据验证
       if(title.includes("上限") || title.includes("下限") || title.includes("申报周期") ){
                 if(!!cellData && !isNumber(cellData)) {
                      this.$message.error(`${title}文件属性请导入数字${cellData}！`);
                      return false;
                 }
            }

            if(title.includes("时间") &&  !title.includes("企业成立时间") ){
                 if(!!cellData && !isDateYYYYMMDD(cellData)) {
                      this.$message.error(`${title}文件属性请导入正确的时间格式如下{2021-08-30}！`);
                      return false;
                 }
            }
            if(title.includes("业务板块") ){
               let business = this.businessList.find(item=>{
                 return item.name == cellData})
              if( !business) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
                //文件编号生成
                this.$set(tableRow, 'prefix',business.code);
                
            } 

             if(!!cellData && title.includes("责任机构") ){

              if( !this.mechanismList.find(item=>{
                 return item.name == cellData
                })) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
            } 

          

            
             if(!!cellData && title.includes("所属专题") ){

              if( !this.specialList.find(item=>{
                 return item.name == cellData
                })) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
            } 
             if(!!cellData && title.includes("政策级别") ){

              if( !this.policylLevel.find(item=>{
                 return item.name == cellData
                })) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
            } 
             if(!!cellData && title.includes("是否长期性政策") ){

              if( !flagDics.find(item=>{
                 return item.name == cellData
                })) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
            } 

            if(title.includes("适用地区") || title.includes("企业注册地") ){
              if(!isArea(cellData)){
                this.$message.error(`${title}文件属性请导入地区格式如下{中国/广东省}${cellData}！`);
                      return false;
              }
              let areaArr = cellData.split("/")
              for (let index = 0; index < areaArr.length; index++) {
                const element = areaArr[index];
                if( !this.areaInfo.includes(element)) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);

                      return false;
                }
              }
              
            } 

            if(!!cellData && title.includes("适用行业（可多选）") ){
                  let industryArr = cellData.split(",")
              if( !this.industryList.find(item=>{
                 return  industryArr.includes(item.industryName) 
                })) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
            } 
            if(!!cellData && title.includes("要求企业资质（可多选）") ){
                 let qualificationArr = cellData.split(",")
              if( !this.qualificationList.find(item=>{
                 return qualificationArr.includes(item.name)
                })) {
                  this.$message.error(`${title}文件属性请导入正确内容${cellData}！`);
                      return false;
                }
            } 
            return true;
    },
    /**
     * 获取分类扩展属性
     */
    fetchClassAttr() {
      const that = this;
      if(!this.classId){return}
      getAction(this.urls.listAttr + '?classId=' + this.classId, {}).then(res => {
        if (res.success) {
          that.classAttrList = res.result;
          
          that.columns = this.parentId == 2 ? cloneDeep(baseColumns) :cloneDeep(baseColumnsNormal);
          that.excelHeader = [];
          res.result.forEach(it => {
            const col = { title: it.name, dataIndex: 'attrs.field_' + it.attrId,required:it.required };
            that.columns.push(col);
          });
          
          // console.log(JSON.stringify(that.columns))
          that.columns.forEach(it => {
                //第一列是序号
            if(it.key == 'rowIndex'){
              return
            }
            that.excelHeader.push(it.title);
          });
        } else {
          this.$message.error('获取分类拓展属性错误');
        }
      });
    },
     handleTemplate() {
      const that = this;
      if(!that.hteFile.classId){
        that.$message.error('请选择文件类型');
        return false
      }
      import('./Export2Excel').then(excel => {
        const tHeader = [];
        that.columns.forEach(it => {
            //第一列是序号
          if(it.key == 'rowIndex'){
            return
          }
          tHeader.push(it.title);
        });
        const data = []; //this.formatJson(filterVal, this.records);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: `${that.label}导入模板`
        });
      });
    },
    
    handleChangeClass(value,label){
     this.classId =value;
     this.label = label;
     this.columns = []
     this.tableData = []
      this.fetchClassAttr();
      this.$emit('changeClass',value);
    }
  }
};
</script>
<style lang="less" scoped>
 /deep/ .j-table-force-nowrap{

    th,td{
    white-space: nowrap !important;
    }
  } 
</style>
